package text;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.Map;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;

import text.traversal.ITextTraversal;

public class TextSet extends Text
{
	private static int name = 0;
	
	protected final List<Text>	textList	= new ArrayList<Text>();
	
	protected final TextSetManager textSetManager;
	
	public TextSetManager getTextSetManager()
	{
		return this.textSetManager;
	}
	
	public List<Text> getTextList()
	{
		return textList;
	}
	
	public int getTextCount()
	{
		return this.textList.size();
	}
	
	public TextSet(TextSetManager textSetManager)
	{
		this("TextSet " + name, textSetManager);
		name++;
	}

	public TextSet(String name, TextSetManager textSetManager)
	{
		super(name, textSetManager);
		
		this.textSetManager = textSetManager;
	}
	
	public void addText(Text text)
	{
		super.addText(text);
		this.textList.add(text);
	}
	
	public void traversalAllText(ITextTraversal traversal)
	{
		for(Text text : textList)
		{
			text.traversal(traversal);
		}
	}
	
	public boolean removeWord(String word)
	{
		for(Text text : this.textList)
		{
			text.removeWord(word);
		}
		
		return super.removeWord(word);
	}
	
	@Override
	public String toString()
	{
		return this.toString(Text.OCCURENCE_INFO);
	}

	public String toString(String info)
	{
		String s = super.toString(info);
		
		s += "All intern text : " + System.getProperty("line.separator");
		for (Text text : this.textList)
		{
			s += text.toString(info);
		}

		return s;
	}
	
	public void parseZip(String filepath) throws IOException
	{
		this.parseZip(filepath, 0, 1, true, null);
	}
	
	public void parseZip(String filepath, double startRatio, double endRatio, boolean inclusive, Map<String, String> translationMap) throws IOException
	{
		ZipFile zip = new ZipFile(filepath);
		Enumeration<? extends ZipEntry> entries = zip.entries();
		
		int entriesCount = 0;
		
		while (entries.hasMoreElements())
		{
			entries.nextElement();
			entriesCount++;
		}
		
		entries = zip.entries();

		int startIndex = (int) (startRatio * entriesCount);
		int endIndex = (int) (endRatio * entriesCount);
		int i = 0;
		while (entries.hasMoreElements())
		{
			ZipEntry entry = entries.nextElement();
			i++;
			
			if(inclusive && i <= startIndex || !inclusive && i < startIndex)
			{
				continue;
			}
			
			if(inclusive && i >= endIndex || !inclusive && i > endIndex)
			{
				break;
			}
			
			//System.out.println("[" + i + "/" + zip.size() + "] reading " + entry.getName());
			
			if (entry.isDirectory())
			{
				continue;
			}
			else
			{
				InputStream is = zip.getInputStream(entry);
				Text text = new Text(entry.getName(), this);
				text.read(is, translationMap);
				this.addText(text);
			}
		}
	}

}
